//
//  CZComposeViewController.swift
//  czbkiosweibo5
//
//  Created by zhangping on 15/10/20.
//  Copyright © 2015年 zhangping. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZComposeViewController: UIViewController {
    
    // MARK: - 属性
    /// 微博文本最大长度
    private let statusMaxLength = 20
    
    /// toolBar底部约束
    private var toolBarBottomCons: NSLayoutConstraint?
    
    /// 照片选择器视图底部约束
    private var photoSelectorViewBottomCons: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        // 控制器的view的背景颜色为nil时,modal出来的过程中可以看到后面的视图,很奇怪
        view.backgroundColor = UIColor.whiteColor()

        prepareUI()
        
        addKeyboardNotification()
    }
    
    // 添加键盘frame改变的通知
    private func addKeyboardNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    private func removeKeyboardNotification() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 注销通知
    deinit {
        removeKeyboardNotification()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 判断 照片选择控制器视图是否显示
        if photoSelectorViewBottomCons?.constant != 0 {
            // 主动弹出键盘
            textView.becomeFirstResponder()
        }
    }
    
    /*
        notification: NSConcreteNotification 0x7fcd851ceaa0 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
            UIKeyboardAnimationCurveUserInfoKey = 7;
            UIKeyboardAnimationDurationUserInfoKey = "0.25";    // 动画时长
            UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
            UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
            UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
            UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
            UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";   // 键盘最终位置
            UIKeyboardIsLocalUserInfoKey = 1;
        }}
    */
    
    // MARK: - 键盘frame改变方法
    /// 键盘frame改变方法
    func keyboardWillChangeFrame(notifiction: NSNotification) {
//        print("notification: \(notifiction)")
        
        // 获取键盘最终的frame
        let endFrame = notifiction.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // toolBar底部到父控件的底部的距离 = 屏幕高度 - 键盘.frame.origin.y
        toolBarBottomCons?.constant = -(UIScreen.height - endFrame.origin.y)
        
        // 获取动画时间
        let duration = notifiction.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        // 动画类型
        let curve = (notifiction.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
//        toolBar.layer.removeAllAnimations()
        
        // toolBar动画
        UIView.animateWithDuration(duration) { () -> Void in
            // 设置动画类型
//            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 准备UI
    /// 准备UI
    private func prepareUI() {
        // 添加子控件
        // textView
        view.addSubview(textView)
        
        // 照片选择器视图
        view.addSubview(photoSelectorVC.view)
        
        // toolBar
        view.addSubview(toolBar)
        
        setupNavigationBar()
        setupTextView()
        preparePhotoSelectorView()
        setupToolBar()
        prepareLengthTipLabel()
    }
    
    /// 准备照片选择器视图
    private func preparePhotoSelectorView() {
        let photoSelectorView = photoSelectorVC.view
        
        // 设置约束
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["psv" : photoSelectorVC.view]
        
        // 左右和父控件重合
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        // 顶部和父控件底部重合
        let photoSelectorViewBottomCons = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: UIScreen.height * 0.6)
        view.addConstraint(photoSelectorViewBottomCons)
        self.photoSelectorViewBottomCons = photoSelectorViewBottomCons
        
        // 高度等于父控件高度0.6
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
    }
    
    /// 准备微博文本长度标签
    private func prepareLengthTipLabel() {
        // 添加子控件
        view.addSubview(lengthTipLabel)
        
        // 添加约束
        lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
        
        lengthTipLabel.text = "\(statusMaxLength)"
    }
    
    /// 设置 textView
    private func setupTextView() {
        /*
            1.控制器在导航控制器里面
            2.scrollView是控制器的view,或者scrollView是控制器view的第一个子view
        */
        // 自动调整scrollView的Insets, 如果有导航栏,调整scrollView.contentInset.top = 64
//        automaticallyAdjustsScrollViewInsets = true

        // 添加约束
        // 在 控制器的view 内部左上角
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        // 在toolBar垂直方向右上角
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
        
        // 添加代理,监听文字改变来设置导航栏右边按钮
        textView.delegate = self
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        // 添加约束
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width, height: 44))
        
        // 获取底部约束
        toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 创建toolBar上的item
        var items = [UIBarButtonItem]()
        
        // 每个item对应的图片名称
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "switchKeyboard"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        var index = 0
        
        // 遍历 itemSettings 创建 UIBarbuttonItem
        for dict in itemSettings {
            // 获取图片名称
            let name = dict["imageName"]!
            let nameHighlight = name + "_highlighted"
            
            // 获取点击事件方法名称
            let action = dict["action"]!
            
            // 创建item
            let item = UIBarButtonItem(imageName: name, highlightedImageName: nameHighlight)
            
            // 添加点击事件
            let button = item.customView as! UIButton
            button.tag = index
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            items.append(item)
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        
        // 删除最后一根弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    /// 设置导航栏
    private func setupNavigationBar() {
        // 导航栏左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        // 导航栏右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        
        // 设置发送按钮为灰色
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置导航栏标题
        setupNavTitle()
    }
    
    /// 设置导航栏标题
    private func setupNavTitle() {
        // 前缀
        let prefix = "发微博"
        
        // 判断是否有用户名称.
        if let name = CZUserAccount.loadAccount()?.screen_name {
            // 有用户名称,拼接用户名称. \n 表示换行
            let titleText = prefix + "\n" + name
            
            // 创建label
            let label = UILabel()
            
            // 显示多行
            label.numberOfLines = 0
            
            // 默认左对齐,改成居中对齐
            label.textAlignment = NSTextAlignment.Center
            
            // 设置内容
//            label.text = titleText
            
            // 创建属性文本
            let attributeText = NSMutableAttributedString(string: titleText)
            
            // 添加属性
            // 发微博3个字添加属性
            // name: 属性名称
            // value: 属性的值
            // range: 哪些范围添加属性
            let range = (titleText as NSString).rangeOfString(prefix)
            attributeText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: range)
            
            // 用户名称添加属性
            let nameRange = (titleText as NSString).rangeOfString(name)
            attributeText.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(11), NSForegroundColorAttributeName: UIColor.lightGrayColor()], range: nameRange)
            
            // 设置属性文本
            label.attributedText = attributeText
            
            // 设置大小
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            // 没有用户名称,直接显示 发微博
            navigationItem.title = prefix
        }
    }
    
    // MARK: - toolBar item 点击事件
    /// 点击选择照片,弹出选择照片视图
    func picture() {
        print("图片")
        
        // 显示 照片选择器
        self.photoSelectorViewBottomCons?.constant = 0
        
        // 隐藏键盘
        textView.resignFirstResponder()
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func trend() {
        print("#")
    }
    
    func mention() {
        print("@")
    }
    
    /*
        在键盘弹出时 textView.inputView == nil 弹出的是系统键盘
    
        键盘正在显示时,不能切换键盘
    */
    func switchKeyboard() {
//        print("表情键盘:\(textView.inputView)")
        
        removeKeyboardNotification()
        
        // 先将键盘退下
        textView.resignFirstResponder()
        
        // 切换键盘
        textView.inputView = textView.inputView == nil ? emoticonVC.view : nil
        
        addKeyboardNotification()
        
        // 再呼出键盘
        textView.becomeFirstResponder()
    }
    
    func add() {
        print("加号")
    }
    
    // MARK: - 点击事件
    /// 关闭控制器
    func close() {
        // 退出键盘
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发微博
    func sendStatus() {
        // 获取textView的文本内容
        let status = textView.emoticonText()
        
        // 判断如果文字超过最大长度,提示用户
        if status.characters.count > statusMaxLength {
            SVProgressHUD.showErrorWithStatus("微博内容超过长度", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        // 获取用户选择的图片
        let image = photoSelectorVC.photos.first
        
        SVProgressHUD.showWithStatus("正在发布微博", maskType: SVProgressHUDMaskType.Black)
        
        // 调用网络工具类发送微博
        CZNetworkTool.sharedInstance.sendStatus(status, image: image) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络繁忙", maskType: SVProgressHUDMaskType.Black)
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("微博发布成功", maskType: SVProgressHUDMaskType.Black)
//            print("微博发送结果: \(result)")
            // 关闭控制器
            self.close()
        }
    }
    
    // MARK: - 懒加载
    /// toolBar
    private lazy var toolBar: UIToolbar = {
        let toolBar = UIToolbar()
        
        // 设置背景颜色
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        return toolBar
    }()
    
    /*
        IOS中用户可以输入文字的控件
            UITextField
                1.只能输入一行文本
                2.有占位文本
                3.继承UIControl不能滚动
    
            UITextView
                1.可以输入多行文本
                2.没有占位文本
                3.继承UIScrollView可以滚动
    */
    /// textView
    private lazy var textView: CZPlaceholderTextView = {
        let textView = CZPlaceholderTextView()

        textView.placeholder = "分享新鲜事..."
        
        // 设置字体大小
        textView.font = UIFont.systemFontOfSize(18)
        
        // 设置contentInset
//        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        // 设置 textView 有回弹效果
        textView.alwaysBounceVertical = true
        
        // 拖动textView关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return textView
    }()
    
    /// 表情控制器
    private lazy var emoticonVC: CZEmoticonViewController = {
        let vc = CZEmoticonViewController()
        self.addChildViewController(vc)
        vc.textView = self.textView
        return vc
    }()
    
    /// 剩余微博文本长度标签
    private lazy var lengthTipLabel = UILabel(textColor: UIColor.lightGrayColor(), fontSize: 12)
    
    /// 照片选择控制器
    private lazy var photoSelectorVC: CZPhotoSelectorViewController = {
        let vc = CZPhotoSelectorViewController()
        
        // 将 vc 添加为 当前控制器的子控制器
        self.addChildViewController(vc)
        
        return vc
    }()
}

// MARK: - 扩展 CZComposeViewController 实现 UITextViewDelegate代理
extension CZComposeViewController: UITextViewDelegate {
    
    // 文字改变代理方法
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 计算剩余文本的长度
        let text = textView.emoticonText()
        
        let length = statusMaxLength - text.characters.count
        
        // 设置文本内容
        lengthTipLabel.text = "\(length)"
        
        // 设置文本颜色, length < 0 红色
        lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
